﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YJKRevitBase.WinForm;
using YJKSump.Kit;
using YJKRevitView;

namespace YJKSump
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdPlaceSump : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			if (Convert.ToInt32(commandData.Application.Application.VersionNumber) < 2014)
			{
				message = "此功能只在Revit2014及其以上版本可用。";
				return Autodesk.Revit.UI.Result.Failed;
			}
			CmdViewType types = (CmdViewType)11;
			if (SwitchView.SetUsableView(types, commandData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			if (CmdPlaceSump._hWndRevit == null)
			{
				CmdPlaceSump._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			if (!new LoadFamily(commandData).LoadSumpFamilys())
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			return this.PlaceSumpLoop(commandData);
		}

		private Result PlaceSumpLoop(ExternalCommandData commandData)
		{
			PlaceSumpForm placeSumpForm = null;
			try
			{
				placeSumpForm = new PlaceSumpForm(commandData.Application.ActiveUIDocument);
				placeSumpForm.Show(CmdPlaceSump._hWndRevit);
			}
			catch (Exception ex)
			{
				YJKMessageBox.Show(ex.Message);
				if (placeSumpForm != null)
				{
					placeSumpForm.Close();
				}
				return Autodesk.Revit.UI.Result.Failed;
			}
			int wMsg = 7;
			CmdPlaceSump.SendMessage(CmdPlaceSump._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			new PlaceSumpKit(commandData).Run(placeSumpForm);
			if (placeSumpForm != null)
			{
				placeSumpForm.Close();
				placeSumpForm = null;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		public static WindowHandle _hWndRevit;
	}
}
